﻿/*
* 站内信
*/
var inMsgGrid
    , outMsgGrid//已发送Grid
    , MsgStore = top.MsgStore//接收到的信息
    , Users = top.Users//用户数据
    , userTree //用户树
    , createLetterWin//新建站内信窗口
    , readLetterWin//阅读站内信窗口
    , roleStore = {
        "88": "主管1"
        , "101": "主管2"
        , "110": "主管3"
        , "42": "监理企业"
        , "15": "施工企业"
        , "76": "县级主管"
        , "86": "市级主管"
        , "96": "省级主管"
        ,"other":"其他"
    }//角色分类
    , userStore = {}//添加索引后的用户库
    , IS_REPLY_OPEN = false//是否开放回复功能
    , MSG_HANDLER_URI = "MsgPushHandler.ashx"//后台地址
    , mainAccordion
    , LETTER_WRITABLE = $("#hidLetterWritable").val()=="true"; //当前用户是否有发送站内信的权限

//初始化
(function () {
    $.ligerDefaults.Grid.formatters['customDate'] = DateFormatConvert;
    InitUser();
    bindReceiverMsgList(top.MsgStore);
    if(LETTER_WRITABLE){
        GetSentMsgList();
    }else{
        document.getElementById("mainAccordion").removeChild(document.getElementById("sendBox"));
    }

    
    var HeightDiff = 3;
    mainAccordion = $("#mainAccordion").ligerAccordion({
        height: top.accordion.accordion.height() - HeightDiff
        ,changeHeightOnResize:true
        ,speed : 0
    });
    
    window.onresize=function(){
        mainAccordion.setHeight(top.accordion.accordion.height() - HeightDiff);
    };

    AddMsgListener();
})();

function AddMsgListener(){
    top.MsgSubscibeEvents[window.name]={
        func:function(data){
            //data是最新消息 暂时用不上
            bindReceiverMsgList(top.MsgStore);
        }
        ,context:window
    };
}

//建立有索引的人员数据列表
function InitUser() {
    for (var i = 0; i < Users.length; i++) {
        userStore[Users[i].UserGuid] = Users[i];
    }
}

function GetSentMsgList() {
    var stamp = new Date() - 0;
    $.get(MSG_HANDLER_URI, { Func: "GetSentMsgs", TimeStamp: stamp }, function (rst) {
        bindSentMsgList(rst);
    }, "json");
}

function bindSentMsgList(data) {
    outMsgGrid = $("#outLetterGrid").ligerGrid({
        width: "860"
        , columns: [
            { display: '收信人', align: 'center', width: 200
                , render: function (item) {
                    return roleStore[item.Receiver] || (userStore[item.Receiver] ? userStore[item.Receiver].Name : null) || roleStore["other"];
                }
            },
            { display: '发送时间', name: 'SendTime', width: 200, type: "customDate" },
            { display: '内容', name: 'MsgText', width: 400 },
            { name: "Receiver", hide: true },
            { name: "ID", hide: true }
        ]
        , rownumbers: true
        , data:{ Rows: data }
        , checkbox: true
        , toolbar: {
            items: [
                { text: '删除', click: DeleteMsgs, icon: 'delete' },
                { line: true },
                {
                    text: '查看'
                    , click: function () {
                        if (outMsgGrid.selected.length > 0) {
                            OpenReadLetterWin(outMsgGrid.selected[0], false);
                        } else {
                            $.ligerDialog.warn("未选择任何信件");
                        }
                    }
                    , icon: 'greenwarn'
                }
            ]
        }
        , enabledSort: false
        , usePager: true
        , isScroll: false
        , selectRowButtonOnly: true
        , onDblClickRow: function (letterData) { OpenReadLetterWin(letterData, false); }
    });
    outMsgGrid.reRender();
}

function DeleteMsgs() {
    var selected = outMsgGrid.selected;
    if (!selected.length) {
        $.ligerDialog.warn("未选择任何信件");
    } else {
        var ids = [];
        for (var i = 0; i < selected.length; i++) {
            ids.push(selected[i].ID);
        }
        $.post(MSG_HANDLER_URI, { Func: "DeleteMsgs", MsgIDs: ids.join(",") }, function (rst) {
            if (rst == "success") {
                $.ligerDialog.alert("删除成功");
                GetSentMsgList();
            } else {
                $.ligerDialog.warn("删除失败");
            }
        });
    }
}

//日期格式转化
function DateFormatConvert(date) {
    var dateStr = date;
    if (typeof date == "object") {
        dateStr = date.toLocaleString();
    } else if (typeof date == "string") {
        dateStr = date;
    }
    return dateStr.replace(/^([\d-]+)T([\d:]+).+$/, "$1 $2");
}

function bindReceiverMsgList(msgs) {
    var items = [];
    
    if (!inMsgGrid) {
        if (LETTER_WRITABLE) {
            items = items.concat([
                { text: '写信', click: OpenCreateLetterWin, icon: 'modify' },
                { line: true }
            ]);
        }
        items.push({ text: '查看', click: onReadBtnClick, icon: 'greenwarn' });

        inMsgGrid = $("#inLetterGrid").ligerGrid({
            width: "860"
            , columns: [
                { display: '发信人', align: 'center', width: 200
                    , render: function (item) {
                        return roleStore[item.Receiver] || (userStore[item.Receiver] ? userStore[item.Receiver].Name : null) || roleStore["other"];
                    }
                },
                { display: '发送时间', name: 'SendTime', width: 200, type: "customDate" },
                { display: '内容', name: 'MsgText', width: 400 },
                { name: "Sender", hide: true }
            ]
            , rownumbers: true
            , checkbox: true
            , toolbar: { items: items }
            , enabledSort: false
            , usePager: true
            , isScroll: false
            , selectRowButtonOnly: true
            , onDblClickRow: function (letterData) { OpenReadLetterWin(letterData, false); }
        });
    }
    inMsgGrid.toggleLoading("show");
    inMsgGrid.loadData({ Rows: msgs });
    inMsgGrid.toggleLoading();
}

/********************获取用户列表***********************/
function CreateUserRoleList() {
    var data = [], roleName, user, roleCount = 1,_roleStoreTemp = {};
    var roleIcon = '../Scripts/ligerUI/skins/icons/myaccount.gif';
    var userIcon = '../Scripts/ligerUI/skins/icons/memeber.gif';
        
    for (var i = 0, len = Users.length; i < len; i++) {
        user = Users[i];
        if (!_roleStoreTemp[user.RoleId]) {
            _roleStoreTemp[user.RoleId] = 1;
            data.push({ id: user.RoleId, pid: 0, text: roleStore[user.RoleId] || roleStore["other"], icon: roleIcon });
        }
        data.push({ id: user.UserGuid, pid: user.RoleId, text: nodeTextToShort(user.Name), icon: userIcon });
    }

    userTree = $("#userTree").ligerTree({
        data: data,
        idFieldName: 'id',
        slide: true,
        parentIDFieldName: 'pid',
        nodeWidth: 280
    });
    userTree.collapseAll();
}

function nodeTextToShort(text) {
    var MAX_NODETEXT_LENGTH = 16;
    if (text.length > MAX_NODETEXT_LENGTH) {
        return text.substring(0, MAX_NODETEXT_LENGTH - 1) + "...";
    }
    return text;
}

function SendMsg(receiver, msg,callBack) {
    $.post(MSG_HANDLER_URI
        , {
            Func: "Send"
            , Users: receiver
            , MsgText: msg
        }
        , function (rst) {
            callBack(rst);
        }
    );
}

function OpenCreateLetterWin(){
    var IsSending = false;
    if (!createLetterWin) {
        createLetterWin = $.ligerDialog.open({
            target: $("#createLetterContainer")
            , title: "新建站内信"
            , width: 600
            , isHidden: true
            , buttons: [
                {
                    text: "关闭"
                    , onclick: function () {
                        createLetterWin.hide();
                    }
                }
                , {
                    text: '发送'
                    , onclick: function () {
                        if (IsSending) return;
                        IsSending = true;
                        var users = GetSelectedUsers();
                        var msgText = $("#createLetterContainer .sendTextContainer").val();
                        if (users.length == 0) {
                            $.ligerDialog.warn("请选择收信人。")
                            return;
                        }
                        SendMsg(users.join(","), msgText, function (rst) {
                            if (rst == "success") {
                                $.ligerDialog.alert("发送成功。");
                                createLetterWin.hide();
                                GetSentMsgList();
                            } else {
                                $.ligerDialog.error("信息发送失败，请稍后重试。")
                            }
                            IsSending = false;
                        });
                    }
                }
            ]
        });
        CreateUserRoleList();
        $("#createLetterContainer .sendTextContainer").val("");
    } else {
        createLetterWin.show();
    }
}

//打开消息详情窗口
function OpenReadLetterWin(letterData, CanReply) {
    var dom = $("#replyLetterContainer"), msgDom = dom.find(".sendTextContainer");

    var btns = [{
        text: "关闭"
        , onclick: function () {
            readLetterWin.hide();
        }
    }];

    $("#oriText").val(letterData.MsgText);


    if (CanReply) {
        msgDom.show().val("");
        btns.push({
            text: '发送'
            , onclick: function () {
                var user = letterData["Sender"];
                SendMsg(user, msgDom.val(), function (rst) {
                    if (rst == "success") {
                        $.ligerDialog.alert("发送成功。");
                        readLetterWin.hide();
                    } else {
                        $.ligerDialog.error("信息发送失败，请稍后重试。")
                    }
                });
            }
        });
    } else {
        msgDom.hide();
    }

    readLetterWin = $.ligerDialog.open({
        target: dom
        , title: "查看"
        , width: 320
        , isHidden: true
        , buttons: btns
    });
}

function onReadBtnClick() {
    if (inMsgGrid.selected.length > 0) {
        OpenReadLetterWin(inMsgGrid.selected[0], false);
    } else {
        $.ligerDialog.warn("未选择任何信件");
    }
}

//获取选中的用户
function GetSelectedUsers() {
    var selected = { RoleIDs: [], UserGuids: [] };
    var checkedNodes = userTree.getChecked();
    var tempStore = {};
    var dataTemp;

    for (var i = 0, len = checkedNodes.length; i < len; i++) {
        dataTemp = checkedNodes[i].data;
        if (!dataTemp.pid == 0) {//人别选择
            if (!tempStore[dataTemp.pid]) {
                tempStore[dataTemp.pid] = [dataTemp.id];
            } else {
                tempStore[dataTemp.pid].push(dataTemp.id);
            }
        } else {//按角色选择
            selected.RoleIDs.push(dataTemp.id);
        }
    }
    for (var i = 0; i < selected.RoleIDs.length; i++) {
        delete tempStore[selected.RoleIDs[i]];
    }
    for (var roleid in tempStore) {
        selected.UserGuids = selected.UserGuids.concat(tempStore[roleid]);
    }
    return selected.RoleIDs.concat(selected.UserGuids);
}
